package com.example.hotel.admin.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hotel.admin.constants.HotelMqConstants;
import com.example.hotel.admin.pojo.Hotel;
import com.example.hotel.admin.pojo.PageResult;
import com.example.hotel.admin.service.HotelService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidParameterException;

@RestController
@RequestMapping("hotel")
public class HotelController {


	@Autowired
	private HotelService hotelService;


	@Autowired
	private RabbitTemplate rabbitTemplate;


	@GetMapping("/{id}")
	public Hotel queryById(@PathVariable("id") Long id) {
		return hotelService.getById(id);
	}

	@GetMapping("/list")
	public PageResult hotelList(
			@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "size", defaultValue = "1") Integer size
	)
	{
		Page<Hotel> result = hotelService.page(new Page<>(page, size));

		return new PageResult(result.getTotal(), result.getRecords());
	}

	@PostMapping
	public void saveHotel(@RequestBody Hotel hotel) {
		// 新增酒店
		hotelService.save(hotel);
		// 发送MQ消息
		rabbitTemplate.convertAndSend(HotelMqConstants.HOTEL_EXCHANGE, HotelMqConstants.hotel_inset_key, hotel.getId());
	}

	@PutMapping()
	public void updateById(@RequestBody Hotel hotel) {
		if (hotel.getId() == null) {
			throw new InvalidParameterException("id不能为空");
		}
		hotelService.updateById(hotel);

		// 发送MQ消息
		rabbitTemplate.convertAndSend(HotelMqConstants.HOTEL_EXCHANGE, HotelMqConstants.hotel_inset_key, hotel.getId());
	}

	@DeleteMapping("/{id}")
	public void deleteById(@PathVariable("id") Long id) {
		hotelService.removeById(id);

		// 发送MQ消息
		rabbitTemplate.convertAndSend(HotelMqConstants.HOTEL_EXCHANGE, HotelMqConstants.hotel_delete_key, id);
	}

}
